using System.Buffers;
using SuperSocketProxy;

namespace SocketPorxyServer;

public sealed class Socket5PacketResponse : IPacketResponse
{
    private static readonly byte Socket5Version = 0x05;

    private readonly SocketProxySession _session;

    public Socket5PacketResponse(SocketProxySession session)
    {
        _session = session;
    }

    ValueTask IPacketResponse.SendHandshakeAsync(bool verifyUser)
    {
        const byte verify = 0x02;
        const byte notVerify = 0x00;

        return _session.SendAsync(writer =>
        {
            writer.WriteByteBigEndian(Socket5Version); //版本

            if (verifyUser)
                writer.WriteByteBigEndian(verify);
            else
                writer.WriteByteBigEndian(notVerify);
        });
    }

    ValueTask IPacketResponse.SendVerifyAsync(bool verifyResult)
    {
        const byte success = 0x00;
        const byte userOrPassError = 0x02;

        return _session.SendAsync(writer =>
        {
            writer.WriteByteBigEndian(Socket5Version); //版本

            if (verifyResult)
                writer.WriteByteBigEndian(success);
            else
                writer.WriteByteBigEndian(userOrPassError);
        });
    }

    ValueTask IPacketResponse.SendConnectAsync(ConnectTargetErrorType connectTargetResult)
    {
        return _session.SendAsync(writer =>
        {
            writer.WriteByteBigEndian(Socket5Version); //版本
            writer.WriteByteBigEndian((byte)connectTargetResult);
        });
    }
    
    ValueTask IPacketResponse.SendConnectAsync(Socket5EndPointPacket packet)
    {
        const byte v1 = 0x00;
        
        return _session.SendAsync(writer =>
        {
            writer.WriteByteBigEndian(Socket5Version);//版本
            writer.WriteByteBigEndian(v1);
            writer.WriteByteBigEndian(v1);
            writer.WriteByteBigEndian((byte)packet.AddressType);//是目标地址类型，有如下取值 0x01 IPv4 ; 0x03 域名 ; 0x04 IPv6
            writer.Write(packet.GetAddressSpan());//地址
            writer.WriteUInt16BigEndian(packet.Port);//端口
        });
    }
    
    ValueTask IPacketResponse.SendConnectHttpAsync()
    {
        throw new NotImplementedException();
    }
}